<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020/9/15 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace common\components\payment;

use Yii;
use yii\base\BaseObject;

class Payment extends BaseObject
{
    const ALIPAY = 'alipay'; // 支付宝
    const WXPAY = 'wxpay'; // 微信
    /** @var object 支付处理类 */
    public $handler = null;
    public $payHandler = '';

    /**
     * 初始化
     */
    public function init()
    {
        if ($this->handler === null && !empty($this->payHandler)) {
            parent::init();
            $handler = $this->payHandler;
            $this->handler = Yii::$app->$handler;
            // 配置支付组件
            $this->handler->setConfig(Yii::$app->config->getItem($handler));
        }
    }

    /**
     * 创建订单号
     * @param int $uid 用户id
     * @return string
     */
    public function createTradeNo($uid)
    {
        $this->init();
        return $this->handler->createTradeNo($uid);
    }

    /**
     * 生成支付订单
     * @param array $order 订单数组
     * @param string $form 生成的订单用处：app，h5等
     * @return mixed
     */
    public function createPayOrder($order = [], $form = 'app')
    {
        $this->init();
        return $this->handler->createPayOrder($order, $form);
    }

    /**
     * 转账接口
     * @param array $order
     * string $order['title'] 订单标题
     * string $order['no'] 商户订单号，64个字符以内，可包含字母、数字、下划线，需保证在商户端不重复
     * string $order['money'] 订单总金额，单位为元
     * string $order['account'] 唯一用户号
     * string $order['remark'] 转账备注
     * @return array
     * @throws \Exception
     */
    public function transMoney($order = [])
    {
        $this->init();
        return $this->handler->transMoney($order);
    }

    /**
     * 查询支付订单
     * @param $tradeNo
     * @return mixed
     */
    public function queryPayOrder($tradeNo)
    {
        $this->init();
        return $this->handler->queryPayOrder($tradeNo);
    }

    /**
     * 异步通知验证
     * @param array $params 异步通知中收到的待验签的所有参数
     * @return boolean
     */
    public function verifyNotify($params = [])
    {
        $this->init();
        return $this->handler->verifyNotify($params);
    }
}